package com.huangd.platform.common.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Date;

public class StreamDrainer {

	private InputStreamReader in;
	private InputStreamReader err;

	private StreamDrainerThread inThread;
	private StreamDrainerThread errThread;

	private StringBuilder content = new StringBuilder();

	private Date date;

	private static final String DEFAULT_ENCODING = "utf8";

	public StreamDrainer() {

	}

	public StreamDrainer(InputStream in, InputStream err) {
		this.in = new InputStreamReader(in, Charset.forName(DEFAULT_ENCODING));
		this.err = new InputStreamReader(err, Charset.forName(DEFAULT_ENCODING));
	}

	public StreamDrainer(InputStream in, InputStream err, String encoding) {
		this.in = new InputStreamReader(in, Charset.forName(encoding));
		this.err = new InputStreamReader(err, Charset.forName(encoding));
	}

	public void reset(InputStream in, InputStream err) {
		this.in = new InputStreamReader(in, Charset.forName(DEFAULT_ENCODING));
		this.err = new InputStreamReader(err, Charset.forName(DEFAULT_ENCODING));
	}

	public void reset(InputStream in, InputStream err, String encoding) {
		this.in = new InputStreamReader(in, Charset.forName(encoding));
		this.err = new InputStreamReader(err, Charset.forName(encoding));
	}

	public void start() {
		inThread = new StreamDrainerThread(in, content);
		errThread = new StreamDrainerThread(err, content);

		inThread.start();
		errThread.start();
	}

	public StringBuilder getContent() {
		try {
			inThread.join();
			errThread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return content;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public static class StreamDrainerThread extends Thread {

		private InputStreamReader isr;

		private StringBuilder content;

		public StreamDrainerThread(InputStreamReader isr, StringBuilder content) {
			this.isr = isr;
			this.content = content;
		}

		@Override
		public void run() {
			try {
				BufferedReader reader = new BufferedReader(isr);

				String line = null;
				while ((line = reader.readLine()) != null) {
					synchronized (content) {
						content.append(line);
						content.append("\n");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				IOUtils.close(isr);
			}
		}
	}
}
